package com.lkx.farmershop.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lkx.farmershop.common.exception.ApiException;
import com.lkx.farmershop.model.dto.UserLoginDTO;
import com.lkx.farmershop.model.entity.User;
import com.lkx.farmershop.mapper.UserMapper;
import com.lkx.farmershop.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author lwc
 * @since 2024-03-21
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RestTemplate restTemplate;

    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    private static final String APPID = "wx626e42ba6c2e97ca";   //APPID
    private static final String SECRET = "2f521063a5452e663fc719bf39189f2b";   //SECRET


    /**
     * 用户微信登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxlogin(UserLoginDTO userLoginDTO) {
        String openid = getOpenid(userLoginDTO);
        //判断openid是否为空，为空表示登录失败，抛出业务异常
        if (StrUtil.isEmpty(openid)) {
            throw new ApiException("登录失败！");
        }
        //判断当前用户是否为新用户
        User user = lambdaQuery().eq(User::getOpenid, openid).one();
        //如果是新用户，自动完成注册
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            save(user);
        }
        //返回这个用户对象
        return user;
    }

    //调用微信接口服务，获得当前微信用户的openid
    private String getOpenid(UserLoginDTO userLoginDTO) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", APPID);
        paramMap.put("secret", SECRET);
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");
        ResponseEntity<String> responseEntity = restTemplate.getForEntity
                (WX_LOGIN + "?grant_type={grant_type}&appid={appid}&js_code={js_code}&secret={secret}"
                        , String.class
                        , paramMap);
        String s = responseEntity.getBody();
        log.info(s);
        //String s = HttpClientUtil.doGet(WX_LOGIN, paramMap);
        //解析返回的JSON字符串
        JSONObject jsonObject = JSON.parseObject(s);
        log.info("openid: {}", jsonObject.getString("openid"));
        return jsonObject.getString("openid");
    }
}
